class_name World extends Node2D
@onready var tile_map: TileMap = $TileMap
@onready var camera: Camera2D = $Player/Camera2D
@onready var player: Player = $Player
@export var bgm : AudioStream

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	var used:= tile_map.get_used_rect().grow(-1)
	var tile_size := tile_map.tile_set.tile_size
	camera.limit_top = used.position.y * tile_size.y
	camera.limit_bottom = used.end.y * tile_size.y
	camera.limit_left = used.position.x * tile_size.x
	camera.limit_right = used.end.x * tile_size.y
	camera.reset_smoothing()
	
	if bgm !=null:
		SoundManager.play_bgm(bgm)

func update_player(pointer:Vector2, direction) ->void:
	player.global_position = pointer
	player.face_direction(direction)
	camera.reset_smoothing()
	camera.force_update_scroll()

# 这里是内存存储，切换场景的时候保持状态
func to_dict() -> Dictionary:
	var enemies_alive := []
	for node in get_tree().get_nodes_in_group("enemies"):
		var path := get_path_to(node)
		enemies_alive.append(path)
		
	return {
		enemies_alive = enemies_alive
	}
func from_dict(dict:Dictionary) -> void:
	for node in get_tree().get_nodes_in_group("enemies"):
		var path := get_path_to(node)
		if path not in dict.enemies_alive:
			node.queue_free()
	
func _unhandled_input(event: InputEvent) -> void:
	if Input.is_action_just_pressed("ui_cancel"):
		Game.back_to_title()
 

func _on_boar_1_died() -> void:
	await get_tree().create_timer(1).timeout
	Game.to_game_end()
